/**
 * SpringMVC restful 风格
 * 订单管理控制器，控制关于订单的一些业务逻辑操作
 * @author yanwl
 * @date 2014-10-08
 */
package com.chnbst.bstyun.controller.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.model.pojo.Meal;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.MealFeeVo;
import com.chnbst.bstyun.model.vo.MealProductVo;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.model.vo.ProductFeeVo;
import com.chnbst.bstyun.service.MealFeeService;
import com.chnbst.bstyun.service.MealProductService;
import com.chnbst.bstyun.service.MealService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.ProductFeeService;
import com.chnbst.bstyun.service.ProductService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.bstyun.service.VoucherService;

@Controller
@RequestMapping("/consume/order")
public class OrderController {
	/**
	 * 每页显示的订单条数
	 */
	private int orderPageSize = 5;
	
	/**
	 * 注入业务逻辑层
	 */
	@Autowired
	private OrderService orderService;
	@Autowired
	private MealService mealService;
	@Autowired
	private ProductService productService;
	@Autowired
	private MealProductService mealProductService;
	@Autowired
	private UserService userService;
	@Autowired
	private ProductFeeService productFeeService;
	@Autowired
	private MealFeeService mealFeeService;
	@Autowired
	private VoucherService voucherService;
	@Autowired
	private PaymentService paymentService;
	
	/**
	 * ajax请求 查询用户订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> selectOrderByUserId(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("userInfo");
		map.put("userId", user.getUserId());
		map.put("isYun", user.getIsYun());
		List<OrderVo> orderList = orderService.selectOrderByUserId(map);
		map.put("orderList", orderList);
		return map;
	}
	
	
	/**
	 * http://xxx.com/consume/order/manage
	 * get请求 查询用户订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/manage",method=RequestMethod.GET)
	public ModelAndView manage(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		
		//所有套餐
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("start", 0);
		map2.put("pageSize", 3);
		map2.put("sortField", "m.add_time");
		map2.put("sortOrder", "asc");
		
		//三个套餐
		List<Meal> meals = mealService.selectMeals(map2);
		
		//应用增值服务产品
		map2.put("sortField", "mp.add_time");
		map2.put("sortOrder", "desc");
		map2.put("pageSize", Integer.MAX_VALUE);
		map2.put("mealId", 4);
		List<MealProductVo> mpVos = mealProductService.selectMealProductVos(map2);
		
		mav.addObject("mpVos", mpVos);
		mav.addObject("meals", meals);
		mav.setViewName("users/consume_record/order_manage/order-list");
		return mav;
	}
	
	
	/**
	 * ajax请求 查询多条件查询用户订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> search(String startTime,String endTime,String proMealId,String orderState,HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("userInfo");
		map.put("userId", user.getUserId());
		map.put("isYun", user.getIsYun());
		String proMealStatus = null;
		if(SignUtil.isEmpty(proMealId)) {
			proMealId = null;
		}else {
			String[] str = proMealId.split("t");
			proMealStatus = str[0];
			proMealId = str[1];
		}
		
		if(SignUtil.isEmpty(orderState)) {
			orderState = null;
		}
		if(SignUtil.isEmpty(startTime)) {
			startTime = null;
		}
		if(SignUtil.isEmpty(endTime)) {
			endTime = null;
		}
		map.put("orderState", orderState);
		map.put("proMealId", proMealId);
		map.put("proMealStatus", proMealStatus);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		
		int totalRows = orderService.selectOrderVoCountByConditions(map);
		
		String pg = request.getParameter("page");
		int currPage = 1;
		if(SignUtil.isNotEmpty(pg)) {
			currPage = Integer.valueOf(pg);
		}
		
		int pageCount = Pager.getPageCount(totalRows, orderPageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, orderPageSize);
		
		map.put("start", start);
		map.put("pageSize", orderPageSize);
		map.put("sortField", "t.order_id");
		map.put("sortOrder", "desc");
		
		
		List<OrderVo> orderList = orderService.selectOrderByConditions(map);
		map.put("orderList", orderList);
		map.put("page", currPage);
		map.put("pageCount", pageCount);
		map.put("totalRows", totalRows);
		return map;
	}
	
	/**
	 * ajax请求 查询已删除的订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/searchDeleteOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> searchDeleteOrder(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("userInfo");
		map.put("userId", user.getUserId());
		
		int totalRows = orderService.selectDeleteOrderVoCountByMap(map);
		
		String pg = request.getParameter("page");
		int currPage = 1;
		if(SignUtil.isNotEmpty(pg)) {
			currPage = Integer.valueOf(pg);
		}
		
		int pageCount = Pager.getPageCount(totalRows, orderPageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, orderPageSize);
		
		map.put("start", start);
		map.put("pageSize", orderPageSize);
		map.put("sortField", "t.order_id");
		map.put("sortOrder", "desc");
		
		
		List<OrderVo> orderList = orderService.selectDeleteOrderVoByMap(map);
		map.put("orderList", orderList);
		map.put("page", currPage);
		map.put("pageCount", pageCount);
		map.put("totalRows", totalRows);
		return map;
	}
	
	/**
	 * http://xxx.com/consume/order/order_detail
	 * get请求 查询用户订单详情
	 * @return 订单详情
	 */
	@RequestMapping(value="/order_detail",method=RequestMethod.GET)
	public ModelAndView order_detail(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		
		Integer orderId = Integer.valueOf(request.getParameter("orderId"));
		OrderVo orderVo = orderService.selectOrderVoByOrderId(orderId);
		
		OrderVo order = new OrderVo();
		
		
		order.setCount(orderVo.getCount());//产品数量
		order.setOrderMoney(orderVo.getOrderMoney());//订单总价
		order.setPayMoney(orderVo.getPayMoney());//应付金额
		
		if(orderVo.getNewProId() != null) {
			ProductFeeVo pf = productFeeService.selectProductFeeVoByProductId(orderVo.getNewProId());
			order.setMealName(pf.getProductName());//产品名称
			
			String dataStr = orderVo.getDataExtend();
			String[] str = dataStr.split("&");
			order.setUseLife(str[0]);//试用年限
			order.setUserNum(Integer.valueOf(str[1]));//用户数
			order.setMealId(Integer.valueOf((int) (pf.getProductFeePrice()/pf.getUserNum()/pf.getUseYear())));//产品单价
		}else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mealId", orderVo.getMealId());
			map.put("start", 0);
			map.put("pageSize", Integer.MAX_VALUE);
			map.put("sortField", "mp.add_time");
			map.put("sortOrder", "asc");
			
			List<MealProductVo> mpv = mealProductService.selectMealProductVos(map);
			String products = "";
			for (int i = 0; i < mpv.size(); i++) {
				products += mpv.get(i).getProductName()+"*1";
				if(i < mpv.size()-1) {
					products += "+";
				}
			}
			
			order.setProductName(products);//套餐产品
			order.setUseLife(orderVo.getUseLife());//试用年限
			order.setUserNum(orderVo.getUserNum());//用户数
			MealFeeVo mf = mealFeeService.selectMealFeeVoByMealId(orderVo.getMealId());
			
			order.setMealName(mf.getMealName());//套餐名称
			
			//单价计算
			int price = 0;
			if(mf.getUserYear() == -1) {
				price = (int) (mf.getPrice()/mf.getUserNum());
			}else {
				price = (int) (mf.getPrice()/mf.getUserNum()/mf.getUserYear());
			}
			order.setMealId(price);//套餐单价
		}
		
		Double voucherPrice = 0.00;
		//代金券金额计算
		if(orderVo.getVoucherNum() != null) {
			voucherPrice = voucherService.selectVoucherByNum(orderVo.getVoucherNum()).getVoucherMoney();
		}
		
		mav.addObject("orderVo", orderVo);
		mav.addObject("order", order);
		mav.addObject("voucherPrice", voucherPrice);
		mav.setViewName("users/consume_record/order_manage/order-detail");
		return mav;
	}
	
	/**
	 * ajax请求 删除订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/deleteOrder",method=RequestMethod.POST)
	@ResponseBody
	public boolean deleteOrder(String orderIds,Integer deleteState,HttpServletRequest request){
		boolean isSuccess = true;
		if(deleteState == 2) {
			deleteState = null;
		}
		if(orderIds.contains(",")) {
			String[] ids = orderIds.split(",");
			for (String str : ids) {
				Order order = orderService.selectOrderByOrderId(Integer.valueOf(str));
				if(!"1".equals(order.getOrderState())) {
					order.setIsDelete(deleteState);
					isSuccess = orderService.updateOrderByOrderId(order);
				}
				
			}
		}else {
			Order order = orderService.selectOrderByOrderId(Integer.valueOf(orderIds));
			if(!"1".equals(order.getOrderState())) {
				order.setIsDelete(deleteState);
				isSuccess = orderService.updateOrderByOrderId(order);
			}
		}
		return isSuccess;
	}
	
	
	/**
	 * ajax请求 取消订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/closeOrder",method=RequestMethod.POST)
	@ResponseBody
	public boolean closeOrder(String orderId,HttpServletRequest request){
		boolean isSuccess = false;
		Integer oId = Integer.valueOf(orderId);
		Order order = orderService.selectOrderByOrderId(oId);
		if(order.getNewProId() == null) {
			User user = userService.selectUserInfoByUserId(order.getUserId());
			userService.deleteUser(user);
			Payment payment = paymentService.selectPaymentByOrderId(oId);
			if(payment != null) {
				payment.setIsCancel(1);
				paymentService.updatePayment(payment);
			}
		}
		order.setOrderState("2");
		isSuccess = orderService.updateOrderByOrderId(order);
		return isSuccess;
	}
	
	/**
	 * ajax请求 检测订单是否是线下支付
	 * @return boolean
	 */
	@RequestMapping(value="/checkOrderIsPayment",method=RequestMethod.POST)
	@ResponseBody
	public boolean checkOrderIsPayment(String orderId,HttpServletRequest request){
		boolean isSuccess = false;
		Integer oId = Integer.valueOf(orderId);
		Payment payment = paymentService.selectPaymentByOrderId(oId);
		if(payment != null) {
			isSuccess = true;
		}
		return isSuccess;
	}
}
